package com.gaowl.yygh.hosp.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.gaowl.yygh.cmn.client.DictFeignClient;
import com.gaowl.yygh.hosp.repository.HospitalRepository;
import com.gaowl.yygh.hosp.service.HospitalService;
import com.gaowl.yygh.model.hosp.Hospital;
import com.gaowl.yygh.vo.hosp.HospitalQueryVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class HospitalServiceImpl implements HospitalService {

    @Autowired
    private HospitalRepository hospitalRepository;

    @Autowired
    private DictFeignClient dictFeignClient;  // 导入dict的远程调用模块

    // 接口1：上传医院
    @Override
    public void save(Map<String, Object> paramMap) {
        //把参数map集合转换为 Hospital对象
        String mapString = JSONObject.toJSONString(paramMap);   // 先转换为字符串
        Hospital hospital = JSONObject.parseObject(mapString, Hospital.class);  // 然后将字符串解析为 Hospital对象

        //判断是否存在数据
        String hoscode = hospital.getHoscode();
        Hospital hospitalExist = hospitalRepository.getHospitalByHoscode(hoscode);

        //如果存在，进行修改
        if (hospitalExist != null) {
            hospital.setStatus(hospitalExist.getStatus());
            hospital.setCreateTime(hospitalExist.getCreateTime());
        } else { //如果不存在，进行添加
            hospital.setStatus(0);
            hospital.setCreateTime(new Date());
        }
        hospital.setUpdateTime(new Date());
        hospital.setIsDeleted(0);
        hospitalRepository.save(hospital);
    }

    // 接口2：查询医院
    @Override
    public Hospital getByHoscode(String hoscode) {
        return hospitalRepository.getHospitalByHoscode(hoscode);
    }

    // 条件分页查询
    @Override
    public Page<Hospital> selectHospPage(Integer page, Integer limit, HospitalQueryVo hospitalQueryVo) {
        // 创建Pageable对象
        Pageable pageable = PageRequest.of(page-1, limit);
        // 创建条件匹配器
        ExampleMatcher matcher = ExampleMatcher.matching()
                .withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING)
                .withIgnoreCase(true);
        // HospitalQueryVo转换为Hospital对象
        Hospital hospital = new Hospital();
        BeanUtils.copyProperties(hospitalQueryVo, hospital);  // 前者是源，后者是目标
        // 创建Example实例
        Example<Hospital> example = Example.of(hospital, matcher);
        // 调用方法实现分页查询
        Page<Hospital> pages= hospitalRepository.findAll(example, pageable);  // 缺乏医院等级信息

        // 远程调用service-cmn服务，查询医院等级信息
        // 获取查询list集合，遍历进行医院等级封装
        pages.getContent().forEach(this::setHospitalHosType);

        return pages;
    }

    // 设置医院等级
    private Hospital setHospitalHosType(Hospital hospital) {
        // 根据dictCode和value查询医院等级
        String hosTypeString = dictFeignClient.getName("Hostype", hospital.getHostype());
        hospital.getParam().put("hostypeString", hosTypeString);

        // 查询省、市、地区等等
        String provinceString = dictFeignClient.getName(hospital.getProvinceCode());
        String cityString = dictFeignClient.getName(hospital.getCityCode());
        String districtString = dictFeignClient.getName(hospital.getDistrictCode());

        hospital.getParam().put("fullAddress", provinceString + cityString + districtString);
        return  hospital;
    }

    // 更新医院状态（上下线）
    @Override
    public void updateStatus(String id, Integer status) {
        // 先通过id查询到医院，修改状态及修改时间，最后保存即可
        Hospital hospital = hospitalRepository.findById(id).get();
        hospital.setStatus(status);
        hospital.setUpdateTime(new Date());
        hospitalRepository.save(hospital);
    }

    // 查看医院详细信息（根据id）
    @Override
    public Map<String, Object> getHospById(String id) {
        HashMap<String, Object> results = new HashMap<>();
        // 设置医院信息（包含医院等级）
        Hospital hospital = this.setHospitalHosType(hospitalRepository.findById(id).get());
        results.put("hospital",hospital);
        //预约规则
        results.put("bookingRule", hospital.getBookingRule());
        hospital.setBookingRule(null);   //不需要重复返回
        return results;
    }

    // 根据hosCode获取医院名称
    @Override
    public String getHospName(String hosCode) {
        return hospitalRepository.getHospitalByHoscode(hosCode).getHosname();
    }

    // 根据医院名称查询具体的医院
    @Override
    public List<Hospital> findByHosname(String hosname) {
        return hospitalRepository.findHospitalByHosnameLike(hosname);
    }

    // 根据医院编号获取 预约挂号详情信息
    @Override
    public Map<String, Object> item(String hoscode) {
        Map<String, Object> result = new HashMap<>();
        Hospital hospital = this.setHospitalHosType(this.getByHoscode(hoscode));
        result.put("hospital", hospital);
        result.put("bookingRule", hospital.getBookingRule());
        hospital.setBookingRule(null);  // 不重复返回
        return result;
    }
}
